package com.yesep.learn.jwt.demo.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.yesep.learn.jwt.demo.model.User;

public class UserDetailsImpl implements UserDetails {

	private static final long serialVersionUID = 1L;

	private User user;

	public UserDetailsImpl(User user) {
		if (null == user) {
			throw new UsernameNotFoundException("用户不存在");
		}
		this.user = user;
	}

	@Override
	public String getUsername() {
		return user.getUsername();
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	/**
	 * 添加用户拥有的权限和角色
	 * 
	 * @return
	 */
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> authorityList = new ArrayList<>();
		Set<String> roles = user.getRoles();// 添加角色
		if (roles != null && roles.size() > 0) {
			roles.forEach(item -> {// lambda表达式
				authorityList.add(new SimpleGrantedAuthority(item));
			});
		}
		return authorityList;
	}

	/**
	 * 账户是否过期
	 * 
	 * @return
	 */
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	/**
	 * 是否禁用
	 * 
	 * @return
	 */
	@Override
	public boolean isAccountNonLocked() {

		return "3".equals(user.getStatus()) ? false : true;
	}

	/**
	 * 密码是否过期
	 * 
	 * @return
	 */
	@Override
	public boolean isCredentialsNonExpired() {

		return true;
	}

	/**
	 * 是否启用
	 * 
	 * @return
	 */
	@Override
	public boolean isEnabled() {

		return "4".equals(user.getStatus()) ? false : true;
	}

}